<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <j-dialog
        title="查询"
        is-mask
        style="width: 40%"
        :visible.sync="crud.props.searchToggle"
      >
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col span="12">
              <el-form-item label="审核日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startAuditDate"
                    align="right"
                    unlink-panels
                    style="width: 50%"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endAuditDate"
                    align="right"
                    unlink-panels
                    style="width: 50%"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="二批">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'二批编码',width: '100'},
                  {prop:'name',label:'二批名称',width: '150'},
                  {prop:'address',label:'地址'},

                  ]"
                  labelKey="name"
                  valueKey="id"
                  :params="{type:3}"
                  width="700"
                  :value.sync="query.sCustomerIds"
                  placeholder="请选择客户"
                  url="api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="客户分类">
                <treeselect
                  v-model="customerTypeIds"
                  :options="customerTypeList"
                  placeholder="客户分类"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'customerTypeList','customerTypeIds')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="销售区域">
                <treeselect
                  v-model="customerAreaIds"
                  :options="areaData"
                  placeholder="销售区域"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'areaData','customerAreaIds')"
                /></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="小计列">
              <el-checkbox-group
                v-model="groupColumn"
                @change="getChange"
                class="flex flex-row flex-wrap"
              >
                <el-checkbox
                  v-for="item in groupColumnList"

                  :label="item.value"
                  :key="item.value"
                  :value="item.value"
                >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="24" class="flex flex-reverse" style="margin-top: 20px">
              <el-button class="filter-item" size="mini" type="primary" @click="queryReport">搜索</el-button>
              <el-button class="filter-item" plain size="mini" type="primary"
                         @click="resetQuery">重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </j-dialog>
      <!--表单组件-->
      <crudOperation :permission="permission" />
      <!--表格渲染-->
      <el-table ref="table" stripe border :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler" show-summary :summary-method="sumRow" @row-click="crud.selectRow" @row-dblclick="toDetail">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/>
        <!--        <el-table-column v-if="columns.visible('customerId')" prop="customerId" label="客户id" />-->
        <el-table-column v-if="groupColumnSelectList.includes('sCustomerId')" prop="sCustomerName" label="二批名称" />
        <el-table-column v-if="groupColumnSelectList.includes('sCustomerId')" prop="sCustomerCode" label="二批编码" />
        <!--        <el-table-column v-if="columns.visible('fCustomerName')" prop="fCustomerName" label="商贸公司姓名" />-->
        <!--        <el-table-column v-if="columns.visible('fCustomerCode')" prop="fCustomerCode" label="商贸公司编码" />-->
        <el-table-column prop="salesBeginFinalBillReceiveAmount" label="销售期初期未账面应收" />
        <el-table-column prop="beginActualReceiveAmount" label="期初应收" />
        <el-table-column prop="thisReceiveAmount" label="本期应收" />
        <el-table-column prop="thisActualReceiptAmount" label="本期实收" />
        <el-table-column prop="finalActualReceiveAmount" label="期末实际应收" />
        <el-table-column prop="unCancelReceiptAmount" label="未核销收款" />
        <el-table-column prop="finalBillReceiveAmount" label="期末账面应收" />

        <!--        <el-table-column prop="salesReceiveBeginAmount" label="销售应收期初金额" />-->
        <!--        <el-table-column prop="salesReceiveAmount" label="销售应收金额" />-->
        <!--        <el-table-column prop="plasticBoxBeginAmount" label="塑箱期初金额" />-->
        <!--        <el-table-column prop="plasticBoxAmount" label="塑箱金额" />-->
        <!--        <el-table-column prop="returnBoxBeginAmount" label="回箱期初总金额" />-->
        <!--        <el-table-column prop="returnBoxAmount" label="回箱总金额" />-->
        <!--        <el-table-column prop="receiptBeginAmount" label="收款期初金额" />-->
        <!--        <el-table-column prop="receiptAmount" label="收款金额" />-->
        <!--        <el-table-column prop="actualReceiveBeginAmount" label="实际应收期初金额" />-->
        <!--        <el-table-column prop="actualReceiveAmount" label="实际应收金额" />-->


        <el-table-column v-if="groupColumnSelectList.includes('customerAreaId')" prop="customerAreaName" label="销售区域" />
        <el-table-column v-if="groupColumnSelectList.includes('customerTypeId')" prop="customerTypeName" label="客户分类" />
        <el-table-column v-if="groupColumnSelectList.includes('saleUserId')" prop="saleUserName" label="业务员" />
        <el-table-column v-if="groupColumnSelectList.includes('pCustomerId')" prop="pCustomerName" label="所属总店" />
        <!--        <el-table-column v-permission="['admin','reportCustomerReceive:edit','reportCustomerReceive:del']" label="操作" width="150px" align="center">-->
        <!--          <template slot-scope="scope">-->
        <!--            <udOperation-->
        <!--              :data="scope.row"-->
        <!--              :permission="permission"-->
        <!--            />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudReportCustomerReceive from '@/api/erp/reportCustomerReceive'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import JDialog from '../../../components/jDialog/jDialog'
import { getCustomerTypeTree } from '@/api/erp/basCustomerType'
import Treeselect from '@riophae/vue-treeselect'
import {getAreaTree} from "@/api/erp/basCustomerArea";
// crud交由presenter持有
const defaultCrud = CRUD({ title: '客户应收报表',
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false,
  },
  query:{
    groupColumns:'sCustomerId'
  },
  queryOnPresenterCreated:false,
  url: 'api/reportSCustomerReceive', sort: '', crudMethod: { ...crudReportCustomerReceive }})
const defaultForm = { id: null, salesReceiveAmount: null, plasticBoxAmount: null, returnBoxAmount: null, receiptAmount: null, actualReceiveAmount: null, customerId: null, customerName: null, customerCode: null, fCustomerId: null, fCustomerName: null, fCustomerCode: null }
export default {
  name: 'ReportCustomerReceive',
  components: { JDialog, pagination, crudOperation, rrOperation, udOperation, Treeselect },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      endBusDate:'',
      startBusDate:'',
      isShow:true,
      customerTypeList: [],
      customerTypeIds: [],
      saleUserIds:[],
      sCustomerIds:[],
      pCustomerIds:[],
      permission: {
        add: ['admin', 'reportCustomerReceive:add'],
        edit: ['admin', 'reportCustomerReceive:edit'],
        del: ['admin', 'reportCustomerReceive:del'],
        import: ['admin', 'reportCustomerReceive:import'],
        export: ['admin', 'reportCustomerReceive:export'],
        copy: ['admin', 'reportCustomerReceive:copy'],
        upload: ['admin', 'reportCustomerReceive:upload'],
        download: ['admin', 'reportCustomerReceive:download'],
      },
      rules: {
      },
      areaData: [],
      groupColumnSelectList: ['sCustomerId'],
      groupColumn: ["sCustomerId"],
      groupColumnList: [
        {
          label: "销售区域",
          value: "customerAreaId",
        },
        {
          label: "客户分类",
          value: "customerTypeId",
        },
        {
          label: "二批",
          value: "sCustomerId",
        },
        {
          label: "业务员",
          value: "saleUserId",
        },
      ],
    }
  },
  created() {
    getCustomerTypeTree({size:999}).then(res=>{
      this.customerTypeList = res
    }),
      this.getDepts()
  },
  mounted(){
    // this.queryReport()
  },
  watch: {
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    sumRow({ columns, data }){
      const sums = []
      for (let i in  columns) {
        if (['beginActualReceiveAmount','thisReceiveAmount','thisActualReceiptAmount','finalActualReceiveAmount',
          'unCancelReceiptAmount','finalBillReceiveAmount','actualReceiveBeginAmount','actualReceiveAmount',
          'plasticBoxBeginAmount','plasticBoxAmount', 'receiptBeginAmount','receiptAmount', 'returnBoxBeginAmount',
          'returnBoxAmount','salesReceiveBeginAmount','salesReceiveAmount','salesBeginFinalBillReceiveAmount'].includes(columns[i].property)) {
          let selectSum = 0
          this.$refs.table.selection.forEach(item => {
            selectSum += item[columns[i].property]
          })
          sums[i] = <p>{selectSum}
            <hr/>
            {this.crud.summary[columns[i].property] || 0}</p>
        }
        sums[0] = <p>选中
          <hr/>
          合计</p>
      }
      return sums
    },
    getDepts() {
      getAreaTree().then(res => {
        this.areaData = res
      })
    },
    getChange(val) {
      this.groupColumnSelectList = val;
      let groupColumn = this.groupColumnSelectList.join(",");
      this.$set(this.query, "groupColumns", groupColumn);
    },
    toDetail(row){
      this.query.startBusDate=this.startBusDate
      this.query.endBusDate=this.endBusDate
      const data = {
        ...this.query,
        customerId:row.customerId,
        sCustomerId:row.sCustomerId,
        customerAreaId:row.customerAreaId,
        customerTypeId:row.customerTypeId,
        saleUserId:row.saleUserId,
        // pCustomerId:row.pCustomerId
      }
      sessionStorage.setItem('reportCustomerReceiveDetail',JSON.stringify(data))
      this.$router.push({
        path: 'reportCustomerReceiveDetail',
        query:{type:1}
      })
    },
    init(){
      this.page = 1
    },
    queryReport(){
      // this.query.saleUserIds = this.saleUserIds.length?this.saleUserIds.join(','):''
      // this.query.pCustomerIds = this.pCustomerIds.length?this.pCustomerIds.join(','):''
      // this.query.sCustomerIds= this.sCustomerIds.length?this.sCustomerIds.join(','):''
      // this.query.groupColumns=this.groupColumnSelectList
      this.endBusDate=this.query.endBusDate
      this.startBusDate=this.query.startBusDate
      this.init()
      this.toQuery()
    },
    toQuery(){
      this.crud.props.searchToggle = false
      this.crud.toQuery()
    },
    resetQuery(){
      this.isShow=false
      this.customerTypeIds = []
      this.customerAreaIds = []
      // this.query = {
      //   saleUserIds : null,
      //   sCustomerIds : null,
      //   pCustomerIds : null,
      // }
      this.saleUserIds = []
      this.sCustomerIds = []
      this.pCustomerIds = []
      this.crud.resetQuery()
      setTimeout(()=>{
        this.isShow = true
      },100)
    },
    getNoStr(val,type,prop){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName(this[type],item)
        str = this.getNode(itemNode,str)
      })
      this.query[prop] = str
    },
    getTreeName(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
